/**
 *
 */
package jp.seraph.same.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import jp.seraph.jsmf.motion.EditableMotion;
import jp.seraph.jsmf.motion.EditableMotionManager;

/**
 *
 */
public class DefaultMotionManagerModel extends AbstractMapHierarchicalViewModel<MotionModel> implements MotionManagerModel {
    public DefaultMotionManagerModel(MotionManagerOpener aOpenner) {
        super("MotionManager");
        mOpener = aOpenner;
        mMotionManager = mOpener.open();
        init(mMotionManager);
    }

    private MotionManagerOpener mOpener;

    private EditableMotionManager mMotionManager;

    private void init(EditableMotionManager aManager) {
        EditableMotionManager tManager = aManager;
        Map<String, MotionModel> tMap = getChildMap();
        List<String> tMotionNameList = new ArrayList<String>();
        for (String tName : tMap.keySet()) {
            tMotionNameList.add(tName);
        }

        for (String tName : tMotionNameList) {
            this.remove(tName);
        }

        List<String> tNames = tManager.getMotionNames();
        for (String tName : tNames) {
            EditableMotion tMotion = tManager.getEditableMotion(tName);
            MotionModel tModel = new DefaultMotionModel(tName, tMotion);

            this.add(tModel);
        }
    }

    /**
     * @see jp.seraph.same.model.MotionManagerModel#open()
     */
    public void open() {
        mMotionManager = mOpener.open();
        init(mMotionManager);
    }

    /**
     * @see jp.seraph.same.model.MotionManagerModel#save()
     */
    public void save() throws IOException {
        mMotionManager.removeAll();

        Set<Entry<String, MotionModel>> tKeyValuePairs = getChildMap().entrySet();
        for (Entry<String, MotionModel> tEntry : tKeyValuePairs) {
            mMotionManager.setMotion(tEntry.getKey(), (EditableMotion) tEntry.getValue().toMotion());
        }

        mMotionManager.save();
    }
}
